package com.fancy.recommendation.controller.internal;

import com.fancy.common.dto.response.Result;
import com.fancy.recommendation.dto.request.UserBehaviorRequestDTO;
import com.fancy.recommendation.dto.response.RecommendationResponseVO;
import com.fancy.recommendation.entity.HotRanking;
import com.fancy.recommendation.entity.Recommendation;
import com.fancy.recommendation.service.RankingService;
import com.fancy.recommendation.service.RecommendationService;
import com.fancy.recommendation.service.UserBehaviorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 推荐服务内部API控制器
 * 提供给其他微服务调用的内部接口
 *
 * @author fancy
 */
@Api(tags = "推荐服务内部API")
@Slf4j
@RestController
@RequestMapping("/api/v1/internal")
@RequiredArgsConstructor
public class InternalRecommendationController {

    private final UserBehaviorService userBehaviorService;
    private final RecommendationService recommendationService;
    private final RankingService rankingService;

    @ApiOperation(value = "记录用户行为", notes = "供其他服务调用记录用户行为")
    @PostMapping("/behaviors")
    public Result<Void> recordUserBehavior(@RequestBody UserBehaviorRequestDTO request) {
        try {
            userBehaviorService.recordBehavior(request);
            return Result.success(null);
        } catch (Exception e) {
            log.error("内部记录用户行为失败", e);
            return Result.fail("记录行为失败");
        }
    }

    @ApiOperation(value = "批量记录用户行为", notes = "供其他服务批量记录用户行为")
    @PostMapping("/behaviors/batch")
    public Result<Void> batchRecordUserBehaviors(@RequestBody List<UserBehaviorRequestDTO> requests) {
        try {
            userBehaviorService.batchRecordBehaviors(requests);
            return Result.success(null);
        } catch (Exception e) {
            log.error("内部批量记录用户行为失败", e);
            return Result.fail("批量记录行为失败");
        }
    }

    @ApiOperation(value = "获取推荐结果", notes = "供其他服务获取用户推荐结果")
    @GetMapping("/recommendations/{userId}")
    public Result<List<RecommendationResponseVO>> getRecommendations(
            @PathVariable Long userId,
            @RequestParam String type,
            @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<Recommendation> recommendations = recommendationService.getCachedRecommendations(userId, type, limit);
            List<RecommendationResponseVO> result = recommendations.stream()
                .map(this::convertToVO)
                .collect(java.util.stream.Collectors.toList());
            return Result.success(result);
        } catch (Exception e) {
            log.error("内部获取推荐结果失败: userId={}", userId, e);
            return Result.fail("获取推荐失败");
        }
    }

    @ApiOperation(value = "更新榜单数据", notes = "供其他服务更新榜单数据")
    @PostMapping("/rankings/update")
    public Result<Void> updateRankingData(@RequestBody List<HotRanking> rankings) {
        try {
            rankingService.batchUpdateRanking(rankings);
            return Result.success(null);
        } catch (Exception e) {
            log.error("内部更新榜单数据失败", e);
            return Result.fail("更新榜单失败");
        }
    }

    @ApiOperation(value = "获取热门内容", notes = "供其他服务获取热门内容")
    @GetMapping("/hot-content/{contentType}")
    public Result<List<Map<String, Object>>> getHotContent(
            @PathVariable String contentType,
            @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<Map<String, Object>> hotContent = rankingService.getRealtimeHotContent(contentType, limit);
            return Result.success(hotContent);
        } catch (Exception e) {
            log.error("内部获取热门内容失败: contentType={}", contentType, e);
            return Result.fail("获取热门内容失败");
        }
    }

    @ApiOperation(value = "获取用户偏好", notes = "供其他服务获取用户偏好信息")
    @GetMapping("/preferences/{userId}")
    public Result<Map<String, Object>> getUserPreferences(@PathVariable Long userId) {
        try {
            Map<String, Object> stats = userBehaviorService.getUserBehaviorStats(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("内部获取用户偏好失败: userId={}", userId, e);
            return Result.fail("获取用户偏好失败");
        }
    }

    @ApiOperation(value = "触发推荐更新", notes = "供其他服务触发用户推荐更新")
    @PostMapping("/recommendations/refresh/{userId}")
    public Result<Void> triggerRecommendationRefresh(@PathVariable Long userId) {
        try {
            recommendationService.refreshUserRecommendations(userId);
            return Result.success(null);
        } catch (Exception e) {
            log.error("内部触发推荐更新失败: userId={}", userId, e);
            return Result.fail("触发推荐更新失败");
        }
    }

    /**
     * 转换为VO对象
     */
    private RecommendationResponseVO convertToVO(Recommendation recommendation) {
        RecommendationResponseVO vo = new RecommendationResponseVO();
        vo.setRecommendationId(recommendation.getId());
        vo.setRecType(recommendation.getRecType());
        vo.setTargetId(recommendation.getTargetId());
        vo.setTargetType(recommendation.getTargetType());
        vo.setScore(recommendation.getScore());
        vo.setReason(recommendation.getReason());
        vo.setAlgorithm(recommendation.getAlgorithm());
        vo.setCreateTime(recommendation.getCreateTime());
        vo.setExpireTime(recommendation.getExpireTime());
        return vo;
    }
}
